package com.example.android.test.project2;

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;

import org.json.JSONException;

import org.json.JSONObject;

import com.example.android.test.project2.MainActivity;
import com.example.android.utils.project2.Utils;

import android.os.Bundle;
import android.os.Handler;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;

public class MainActivity extends Activity {

  public final static String ERROR_MESSAGE = "com.example.android.text.project2.MESSAGE";
  public final static String USERNAME = "com.example.android.text.project2.USERNAME";
  public final static String FIRSTNAME = "com.example.android.text.project2.FIRSTNAME";
  public final static String LASTNAME = "com.example.android.text.project2.LASTNAME";

  private JSONObject jsonResult = null;
  ProgressDialog dialog;

  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Get the message from the intent
    Intent intent = getIntent();
    setContentView(R.layout.activity_main);
    if (intent != null) {
      ArrayList<String> errors = intent
          .getStringArrayListExtra(MainActivity.ERROR_MESSAGE);
      if (errors != null && !errors.isEmpty()) {
        // Error message has to be displayed
        RelativeLayout rView = (RelativeLayout) findViewById(R.id.loginLayout);
        for (int i = 0; i < errors.size(); i++) {
          TextView errorText = new TextView(this);
          errorText.setText(errors.get(i));
          errorText.setTextColor(Color.parseColor("#FF0000"));
          errorText.setId(i + 1);
          // TODO -- This has to be added to Layout
          RelativeLayout.LayoutParams lParms = new RelativeLayout.LayoutParams(
              RelativeLayout.LayoutParams.WRAP_CONTENT,
              RelativeLayout.LayoutParams.WRAP_CONTENT);
          int elementId = (i == 0) ? R.id.button1 : i;
          lParms.addRule(RelativeLayout.BELOW, elementId);
          lParms.addRule(RelativeLayout.CENTER_HORIZONTAL);
          rView.addView(errorText, lParms);
          // setting username if present
          String username = intent.getStringExtra(MainActivity.USERNAME);
          if (username != null) {
            EditText usernameText = (EditText) findViewById(R.id.username);
            usernameText.setText(username);
          }
        }
      }
    }
  }

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
  }

  public void processLogin(View view) {
    EditText usernameText = (EditText) findViewById(R.id.username);
    String username = usernameText.getText().toString();
    EditText passwordText = (EditText) findViewById(R.id.password);
    String password = passwordText.getText().toString();
    ArrayList<String> errors = new ArrayList<String>();
    // Validating data input
    if (username == null || username.trim().isEmpty()) {
      errors.add(getString(R.string.username_error));
    }
    if (password == null || password.trim().isEmpty()) {
      errors.add(getString(R.string.password_error));
    }
    Intent intent;
    if (errors.isEmpty()) {
      // proceed to verify username or password
      dialog = ProgressDialog.show(MainActivity.this, "", "Please wait...");

      // //////////////////////
      // Background Processing 
      /*
      jsonResult = null;
      Thread thread = new Thread(null, doBackgroundThreadProcessing,
          "Background");
      thread.start();
*/
      // //////////////////////
      // username and password verified
      intent = new Intent(this, DisplayTabActivity.class);
      startActivity(intent);
      ////////////////////////////////
    } else {
      intent = new Intent(this, MainActivity.class);
      intent.putStringArrayListExtra(ERROR_MESSAGE, errors);
      intent.putExtra(USERNAME, username);
      intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
      startActivity(intent);
    }

  }

  // Do background processing runnable
  private Runnable doBackgroundThreadProcessing = new Runnable() {
    public void run() {
      backgroundThreadProcessing();
    }
  };
  // Initialize handler
  private Handler handler = new Handler();

  // Runnable to execute Update GUI
  private Runnable doUpdateGUI = new Runnable() {
    public void run() {
      updateGUI();
    }
  };

  // Method to do processing in the background
  private void backgroundThreadProcessing() {
    jsonResult = getJSONData();
    handler.post(doUpdateGUI);
  }

  // Method to update GUI
  private void updateGUI() {
    dialog.dismiss();
    Intent intent = new Intent(this, ResultsPageActivity.class);
    try {
      JSONObject json = jsonResult.getJSONObject("data");
      String firstName = (String) json.getString("firstName");
      String lastName = (String) json.getString("lastName");
      intent.putExtra(FIRSTNAME, firstName);
      intent.putExtra(LASTNAME, lastName);
    } catch (JSONException e) {
      Log.e(
          this.getClass().getName(),
          "An error occurred while trying to retrieve JSON data -- "
              + e.toString());
    }
    startActivity(intent);
  }

  /*
   * public void postData() { // Create a new HttpClient and Post Header
   * HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new
   * HttpPost("http://www.yoursite.com/script.php");
   * 
   * try { // Add your data List<NameValuePair> nameValuePairs = new
   * ArrayList<NameValuePair>(2); nameValuePairs.add(new
   * BasicNameValuePair("id", "12345")); nameValuePairs.add(new
   * BasicNameValuePair("stringdata", "AndDev is Cool!"));
   * httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
   * 
   * // Execute HTTP Post Request HttpResponse response =
   * httpclient.execute(httppost);
   * 
   * } catch (ClientProtocolException e) { // TODO Auto-generated catch block }
   * catch (IOException e) { // TODO Auto-generated catch block } }
   */

  public JSONObject getJSONData() {
    StringBuilder request = null;
    JSONObject json = null;
    try {
      //URL url = new URL("http://www.treadstoneweb.com/serviceJson.php");
      URL url = new URL("http://www.treadstoneweb.com/serviceJson.php?firstName=Henry&lastName=Smith");
      // Create a new HTTP URL connection
      URLConnection connection = url.openConnection();
      HttpURLConnection httpConnection = (HttpURLConnection) connection;
     // httpConnection.setRequestProperty("firstName", "Henry");
     // httpConnection.setRequestProperty("lastName", "Smith");
      int responseCode = httpConnection.getResponseCode();
      if (responseCode == HttpURLConnection.HTTP_OK) {

        InputStream in = httpConnection.getInputStream();
        request = Utils.inputStreamToString(in);
        // Format JSON result
        if (request != null) {
          json = new org.json.JSONObject(request.toString());
        }
      }
    } catch (MalformedURLException e) {
      Log.d(this.getClass().getName(), "Malformed URL Exception");
    } catch (IOException e) {
      Log.d(this.getClass().getName(), "IO Exception");
    } catch (Exception e) {
      Log.d(this.getClass().getName(), "Exception occurred: " + e.toString());
    }
    return json;
  }

}
